#include <sum_csr.h>

// 外部中断入口
__attribute__((interrupt, aligned(4))) void irqentry_exti(void) {
	u32_s saved_mepc, saved_mcause, saved_msubm;
	// 保存CSR寄存器
	__asm__("csrr %0, %1" : "=r"(saved_mepc) : "i"(CSR_MEPC));
	__asm__("csrr %0, %1" : "=r"(saved_mcause) : "i"(CSR_MCAUSE));
	__asm__("csrr %0, %1" : "=r"(saved_msubm) : "i"(CSR_MSUBM));
	// 处理中断（含自动保存通用寄存器）
	__asm__("csrrw ra, %0, ra" ::"i"(CSR_JALMNXTI)
		: "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "t0", "t1",
		  "t2", "t3", "t4", "t5", "t6", "ra");
	// 关闭全局中断（保险起见）
	csr_disable_global_interrupt();
	// 恢复CSR寄存器
	__asm__("csrw %0, %1" ::"i"(CSR_MSUBM), "r"(saved_msubm));
	__asm__("csrw %0, %1" ::"i"(CSR_MCAUSE), "r"(saved_mcause));
	__asm__("csrw %0, %1" ::"i"(CSR_MEPC), "r"(saved_mepc));
	// 程序会自动恢复通用寄存器
}
